<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>产品关联门票</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="__CSS__/admin.css" media="all">
    <style>
        .packageChild{
            margin: 16px;
        }
        .layui-inline{
            margin: 0 !important;
        }
        .layui-input{
            display: inline-block;
        }
        .ticketCurrency{
            margin-left: 10px !important;
        }
        .ticketCurrencyCode,.ticketRate{
            color:green;
        }
    </style>
</head>
<body>
<div style="margin-top: 20px;">
</div>
<form class="layui-form" id="admin">
    <div>
        <div class="layui-form-item packageChild">
            <!--门票检索提示-->
            <blockquote class="layui-elem-quote">
                <span style="color:red;font-size:16px">门票检索请输入关键字后按回车,默认门票的总成本为【淡季总成本】</span>
            </blockquote>
            <span class="layui-btn  layui-btn-sm layui-btn-normal addTicket" style="margin-top: 4px">新增</span>
            <div class="layui-form-item childs">
                <div class="" style="">
                    <table class="layui-table">
                        <colgruop>
                            <col width="10%">
                            <col width="10%">
                            <col width="14%">
                            <col width="45%">
                            <col width="8%">
                            <col width="8%">
                            <col width="5%">
                        </colgruop>
                        <thead>
                        <tr>
                            <th>第几天</th>
                            <th>关联POI</th>
                            <th>关联门票</th>
                            <th>套餐类型</th>
                            <th>总成本</th>
                            <th>总销售价</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody class="ticketBody">
                        {volist name='ticketJson' id='value'}
                        <tr class="singleTicket">
                            <td>
                                <select name="days" lay-filter="days" lay-search="" required>
                                    <option value="">请选择天数</option>
                                    {volist name='productData' id='days'}
                                    <option value="{$days.displayorder}" {if $days.displayorder==$value.days}selected{/if} >第{$days.displayorder}天</option>
                                    {/volist}
                                </select>
                            </td>
                            <td>
                                <select name="poi_id" lay-filter="poi_id" lay-search="" required>
                                    <option value="">请选择关联POI</option>
                                    {volist name='productData' id='days'}
                                    {if $days.displayorder==$value.days}
                                    {volist name='$days.actives' id='poi'}
                                    <option value="{$poi.poiid}" {if $poi.poiid==$value.poi_id}selected{/if} >{$poi.poiname}</option>
                                    {/volist}
                                    {/if}
                                    {/volist}
                                </select>
                            </td>
                            <td class="selectTicket">
                                <select name="ticket_id" lay-filter="ticket_id" lay-search="" required>
                                    <option value="">请选择门票产品</option>
                                    <option value="{$value.ticket_id}" selected >{$value.name}</option>
                                </select>
                            </td>

                            <td>
                                <div>
                                    <a class="addSpec layui-btn layui-btn-normal layui-btn-sm">新增</a>
                                    <div class="layui-inline ticketCurrency">单位：<span class="ticketCurrencyCode">{$value.currency}</span></div>
                                    <div class="layui-inline ticketCurrency">销售系数：<span class="ticketRate">{$value.rate}</span></div>
                                    <input type="hidden" name="ticketCurrencyCode" value="{$value.currency}">
                                    <input type="hidden" name="ticketRate" value="{$value.rate}">
                                    <input type="hidden" name="ticketName" value="{$value.name}">
                                </div>

                                <table class="layui-table">
                                    <colgruop>
                                        <col width="20%">
                                        <col width="20%">
                                        <col width="20%">
                                        <col width="18%">
                                        <col width="18%">
                                        <col width="4%">
                                    </colgruop>
                                    <thead>
                                    <tr>
                                        <th>套餐</th>
                                        <th>规格</th>
                                        <th>人数</th>
                                        <th>成本价</th>
                                        <th>销售价</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody class="specBody">
                                        {volist name='value.specsData' id='spec'}
                                        <tr>
                                            <td>
                                                <select name="packages" lay-filter="packages" class="layui-select" lay-search="" required>
                                                    <option value="">请选择套餐</option>
                                                    <option value="{$spec.package_id}" selected >{$spec.p_name}</option>
                                                </select>
                                            </td>
                                            <td>
                                                <select name="specs" lay-filter="specs" class="layui-select" lay-search="" required>
                                                    <option value="">请选择规格</option>                                                    <option value="">请选择套餐</option>
                                                    <option value="{$spec.spec_id}" selected >{$spec.s_name}</option>
                                                </select>
                                            </td>
                                            <td>
                                                <span class="layui-inline" style="width:15%;">x</span>
                                                <input style="width: 60%;" class="layui-input layui-inline" type="number" max="99" min="1" name="people_num" value="{$spec.people_num}" step="1" placeholder="人数" required>
                                            </td>
                                            <td>
                                                <input class="layui-input" type="number" name="cost" value="{$spec.cost}" readonly required>
                                            </td>
                                            <td>
                                                <input class="layui-input" type="number" name="sale_price" value="{$spec.sale}" readonly required>
                                            </td>
                                            <td>
                                                <a class="delSpec layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon"></i></a>
                                            </td>
                                        </tr>
                                        {/volist}
                                    </tbody>
                                </table>
                            </td>
                            <td>
                                <input type="text" name="total_cost" class="layui-inline layui-input" value="{$value.cost}" readonly required>
                            </td>
                            <td>
                                <input type="text" name="total_sale_price" class="layui-inline layui-input" value="{$value.sale}" readonly required>
                            </td>
                            <td>
                                <span class="layui-btn layui-btn-danger layui-btn-sm delTicket" data-id="" style="margin-top: 4px"><i class="layui-icon"></i></span>
                            </td>
                        </tr>
                        {/volist}
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="layui-form-item">
                <button class="layui-btn" lay-submit lay-filter="submit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </div>

</form>

<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>
<script>
    {if !empty($ticketData)}
    var ticketData = {$ticketData};
    {else}
    var ticketData = [];
    {/if}
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form;
        //渲染天数
        function renderDyas(_that,val=''){
            var days_html = "";
            $.each(ticketData,function(i,v){
                var selected = "";
                if(val!=='' && v.displayorder==val){
                    selected = "selected";
                }
                days_html += "<option "+selected+" value='"+v.displayorder+"'>第"+v.displayorder+"天</option>"
            })
            $(_that).find('select[name=days]').append(days_html);
            //重新绑定
            bindSearchTicketEvent();
        }

        //点击天数切换POI列表
        form.on('select(days)',function(param){
            var value = param.value;
            var _that = this;
            $.each(ticketData,function(i,v){
                if(v.displayorder==value){
                    var poi_html = '';
                    $.each(v.actives,function (ii,vv) {
                        poi_html += '<option value="'+vv.poiid+'">'+vv.poiname+'</option>'
                    })
                    $(_that).parent().parent().parent().next().find('select[name=poi_id] option:not(:first-child)').remove()
                    $(_that).parent().parent().parent().next().find('select[name=poi_id]').append(poi_html)
                    //重新绑定
                    bindSearchTicketEvent();
                    return false;
                }
            })
        })

        //
        //添加门票
        $('.addTicket').click(function(){
            var html = '<tr class="singleTicket">\n' +
                '                            <td>\n' +
                '                                <select name="days" lay-filter="days" lay-search="" required>\n' +
                '                                    <option value="">请选择天数</option>\n' +
                '                                </select>\n' +
                '                            </td>\n' +
                '                            <td>\n' +
                '                                <select name="poi_id" lay-filter="poi_id" lay-search="" required>\n' +
                '                                    <option value="">请选择关联POI</option>\n' +
                '\n' +
                '                                </select>\n' +
                '                            </td>\n' +
                '                            <td class="selectTicket">\n' +
                '                                <select name="ticket_id" lay-filter="ticket_id" lay-search="" required>\n' +
                '                                    <option value="">请选择门票产品</option>\n' +
                '\n' +
                '                                </select>\n' +
                '                            </td>\n' +
                '\n' +
                '                            <td>\n' +
                '                                <div>\n' +
                '                                    <a class="addSpec layui-btn layui-btn-normal layui-btn-sm">新增</a>\n' +
                '                                    <div class="layui-inline ticketCurrency">单位：<span class="ticketCurrencyCode">CNY</span></div>\n' +
                '                                    <div class="layui-inline ticketCurrency">销售系数：<span class="ticketRate">1</span></div>\n' +
                '                                    <input type="hidden" name="ticketCurrencyCode" value="CNY">\n' +
                '                                    <input type="hidden" name="ticketRate" value="1">\n' +
                '                                    <input type="hidden" name="ticketName" value="">\n' +
                '                                </div>\n' +
                '                                <table class="layui-table">\n' +
                '                                    <colgruop>\n' +
                '                                        <col width="20%">\n' +
                '                                        <col width="20%">\n' +
                '                                        <col width="20%">\n' +
                '                                        <col width="17%">\n' +
                '                                        <col width="18%">\n' +
                '                                        <col width="5%">\n' +
                '                                    </colgruop>\n' +
                '                                    <thead>\n' +
                '                                    <tr>\n' +
                '                                        <th>套餐</th>\n' +
                '                                        <th>规格</th>\n' +
                '                                        <th>人数</th>\n' +
                '                                        <th>成本价</th>\n' +
                '                                        <th>销售价</th>\n' +
                '                                        <th>操作</th>\n' +
                '                                    </tr>\n' +
                '                                    </thead>\n' +
                '                                    <tbody class="specBody">\n' +
                '                                        <tr>\n' +
                '                                            <td>\n' +
                '                                                <select name="packages" lay-filter="packages" class="layui-select" lay-search="" required>\n' +
                '                                                    <option value="">请选择套餐</option>\n' +
                '                                                </select>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <select name="specs" lay-filter="specs" class="layui-select" lay-search="" required>\n' +
                '                                                    <option value="">请选择规格</option>\n' +
                '                                                </select>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <span class="layui-inline" style="width:15%;">x</span>\n' +
                '                                                <input style="width: 60%;" class="layui-input layui-inline" type="number" max="99" min="1" name="people_num" value="1" step="1" placeholder="人数" required>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <input class="layui-input" type="number" name="cost" value="" readonly required>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <input class="layui-input" type="number" name="sale_price" value="" readonly required>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <a class="delSpec layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon"></i></a>\n' +
                '                                            </td>\n' +
                '                                        </tr>\n' +
                '                                    </tbody>\n' +
                '                                </table>\n' +
                '                            </td>\n' +
                '                            <td>\n' +
                '                                <input type="text" name="total_cost" class="layui-inline layui-input" value="" readonly required>\n' +
                '                            </td>\n' +
                '                            <td>\n' +
                '                                <input type="text" name="total_sale_price" class="layui-inline layui-input" value="" readonly required>\n' +
                '                            </td>\n' +
                '                            <td>\n' +
                '                                <span class="layui-btn layui-btn-danger layui-btn-sm delTicket" data-id="" style="margin-top: 4px"><i class="layui-icon"></i></span>\n' +
                '                            </td>\n' +
                '                        </tr>';
            //增加ticket节点
            $('.ticketBody').append(html);
            renderDyas($('.ticketBody :last-child'));
            //重新绑定
            bindSearchTicketEvent();
        })
        //添加门票套餐
        $(document).on('click','.addSpec',function(){
            var html = '<tr>\n' +
                '                                            <td>\n' +
                '                                                <select name="packages" lay-filter="packages" class="layui-select" lay-search="">\n' +
                '                                                    <option value="">请选择套餐</option>\n' +
                '                                                </select>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <select name="specs" lay-filter="specs" class="layui-select" lay-search="">\n' +
                '                                                    <option value="">请选择规格</option>\n' +
                '                                                </select>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <span class="layui-inline" style="width:15%;">x</span>\n' +
                '                                                <input style="width: 60%;" class="layui-input layui-inline" type="number" max="99" min="1" name="people_num" value="1" step="1" placeholder="人数">\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <input class="layui-input" type="number" name="cost" value="" readonly>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <input class="layui-input" type="number" name="sale_price" value="" readonly>\n' +
                '                                            </td>\n' +
                '                                            <td>\n' +
                '                                                <a class="delSpec layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon"></i></a>\n' +
                '                                            </td>\n' +
                '                                        </tr>';
            //增加spec节点
            // console.log($(this).parent().parent().find('.specBody'))
            $(this).parent().parent().find('.specBody').append(html);
            //获取
            var product_id = $(this).attr('data-id');
            var selector = $(this).parent().parent().find('.specBody').find('select[name=packages]:last-child');
            console.log(selector,product_id);
            renderProductPackages(selector,product_id)
            //重新绑定
            bindSearchTicketEvent();
        })
        //删除门票
        $(document).on('click','.delTicket',function(){
            var data_id = $(this).attr('data-id');
            if(data_id > 0){
                //执行删除请求
            }else{
                //删除节点
                $(this).parent().parent().remove();
                layer.msg('删除成功');
            }

        })
        //删除门票套餐
        $(document).on('click','.delSpec',function(){
            var data_id = $(this).attr('data-id');
            if(data_id > 0){
                //执行删除请求
            }else{
                //删除节点
                $(this).parent().parent().remove();
                layer.msg('删除成功');
            }
        })

        bindSearchTicketEvent();
        //绑定搜索门票事件
        function bindSearchTicketEvent(){
            //顺序不可调换 先渲染select
            form.render('select');
            //再绑定事件
            $(".selectTicket input").on('keyup',selectTicketId);
        }

        // 绑定门票输入事件
        function selectTicketId(e){
            if(e.keyCode!=13){
                return false;
            }
            var keyword = $(this).val();
            if(keyword===''){
                return false;
            }
            var _that = this;
            $(_that).parent().parent().parent().find('option:not(:first)').remove();
            //请求门票数据
            $.post("{:url('admin/ticket/searchTicketProduct')}",{keyword:keyword},function(res){
                layer.msg(res.msg);
                if(res.code>0){
                    var selector = $(_that).parent().parent().parent().find('select');
                    var html = '';
                    $.each(res.data,function (i,v) {
                        html += '<option value="'+v.id+'" data-rate="'+v.ticket_rate+'" data-currency="'+v.currency+'">'+v.id+'-'+v.name+'-'+v.item_num+'</option>';
                    })
                    $(selector).append(html);
                    form.render('select');//不可删除 为下面获取焦点做准备
                    //获取焦点 input会重新生成
                    $(selector).next().addClass("layui-form-selected");
                    $(selector).next().find('input').focus();
                    $(selector).next().find('input').val(keyword);
                    //重新绑定
                    $(".selectTicket input").on('keyup',selectTicketId);
                }
            },'json')
        }
        //渲染门票套餐
        function renderProductPackages(selector,product_id)
        {
            if(selector.length>1){
                $.each(selector,function (i,v) {
                    $(v).find('option:not(:first)').remove();
                })
            }else{
                $(selector).find('option:not(:first)').remove();
            }

            $.post("/admin/ticket/ticketPackage?product_id="+product_id,{},function(res){
                if(res.code>0){
                    var html = '';
                    $.each(res.data,function (i,v) {
                        html += '<option value="'+v.id+'" >'+v.name+'</option>';
                    })

                    if(selector.length>1){
                        $.each(selector,function (i,v) {
                            $(v).append(html);
                        })
                    }else{
                        $(selector).append(html);
                    }
                    //重新绑定
                    bindSearchTicketEvent();
                }
            },'json')
        }
        var specs = [];
        //渲染门票规格
        function renderProductSpecs(_that,package_id)
        {
            var selector = $(_that).find('select[name=specs]');
            $(_that).find('select[name=specs] option:not(:first)').remove();
            $.post("/admin/ticket/ticketSpec?package_id=" + package_id,{},function(res){
                if(res.code>0){
                    var html = '';
                    specs = res.data;
                    $.each(res.data,function (i,v) {
                        html += '<option value="'+v.id+'">'+v.name+'</option>';
                    })
                    $(selector).append(html);
                    //重新绑定
                    bindSearchTicketEvent();
                }
            },'json')
        }
        // 选择门票渲染套餐
        form.on('select(ticket_id)',function (data) {
            var value = data.value;
            var ticketRate = 1;
            var ticketCurrency = 'CNY';
            var ticketName = '';
            //获取渲染前的select
            var options = $(this).parent().parent().parent().find('select[name=ticket_id] option');
            var packages = $(this).parent().parent().parent().next();
            console.log(packages);
            $.each(options,function (i,v) {
                if($(v).attr('value') == value){
                    ticketRate = $(v).attr('data-rate');
                    ticketCurrency = $(v).attr('data-currency');
                    ticketName = $(v).text();
                    return false;
                }
            })

            $(packages).find('.addSpec').attr('data-id',value).attr('data-rate',ticketRate).attr('data-currency',ticketCurrency);
            $(packages).find('.ticketCurrencyCode').html(ticketCurrency);
            $(packages).find('.ticketRate').html(ticketRate);
            $(packages).find('input[name=ticketCurrencyCode]').val(ticketCurrency);
            $(packages).find('input[name=ticketRate]').val(ticketRate);
            $(packages).find('input[name=ticketName]').val(ticketName);
            var selector = $(packages).find('select[name=packages]');
            renderProductPackages(selector,value);
        })
        // 选择门票套餐渲染规则
        form.on('select(packages)',function (data) {
            var value = data.value;
            var specs = $(this).parent().parent().parent().next();
            console.log(specs);
            renderProductSpecs(specs,value);
        })

        // 选择门票规格
        form.on('select(specs)',function (data) {
            var value = data.value;
            var ticketRate = $(this).parent().parent().parent().parent().parent().parent().parent().find('.addSpec').attr('data-rate');
            var cost = $(this).parent().parent().parent().next().next();
            var sale_price = $(this).parent().parent().parent().next().next().next();
            console.log(ticketRate,value,sale_price);
            $.each(specs,function (i,v) {
                if(v.id==value){
                    $(cost).find('input[name=cost]').val(v.off_season_ref_price);
                    var sale_price_value = parseFloat(v.off_season_ref_price)*parseFloat(ticketRate);
                    $(sale_price).find('input[name=sale_price]').val(sale_price_value.toFixed(2));
                    return false;
                }
            })
            var that = $(this).parent().parent().parent().parent().parent().parent().parent();
            caculateTotalPrice(that);
        })

        //更新总成本和总销售价 _that代表大表格td
        function caculateTotalPrice(_that)
        {
            var totalCostPrice = 0;
            var totalSalePrice = 0;
            //获取当前的td的所有内容
            var tr = $(_that).find('.specBody tr');
            $.each(tr,function(i,v){
                var num = $(v).find('input[name=people_num]').val();
                var costprice = $(v).find('input[name=cost]').val();
                var saleprice = $(v).find('input[name=sale_price]').val();

                totalCostPrice += parseFloat(costprice)*num;
                totalSalePrice += parseFloat(saleprice)*num;
            })

            $(_that).next().find('input[name=total_cost]').val(totalCostPrice.toFixed(2));
            $(_that).next().next().find('input[name=total_sale_price]').val(totalSalePrice.toFixed(2));
        }
        //绑定修改人数计算总价
        $(document).on('input','input[name=people_num]',function(){
            var that = $(this).parent().parent().parent().parent().parent();
            caculateTotalPrice(that);
        })

        //检测数据是否完整
        function checkAllData()
        {
            var jsonData = [];
            var ticketList = $('.ticketBody>tr');
            if(ticketList.length<1){layer.msg('请添加门票内容');return false;}
            var errmsg = '';
            //遍历所有门票
            $.each(ticketList,function (i,v) {
                var days = $(v).find('select[name=days]').val();
                if(days==''){errmsg='请检查选择天数';return false;}
                var poi_id = $(v).find('select[name=poi_id]').val();
                if(poi_id==''){errmsg='请检查选择POI';return false;}
                var ticket_id = $(v).find('select[name=ticket_id]').val();
                if(ticket_id==''){errmsg='请检查选择门票';return false;}
                var currencyCode = $(v).find('input[name=ticketCurrencyCode]').val();
                var rate = $(v).find('input[name=ticketRate]').val();
                var name = $(v).find('input[name=ticketName]').val();
                var costPrice = $(v).find('input[name=total_cost]').val();
                var salePrice = $(v).find('input[name=total_sale_price]').val();
                var specsData = [];
                //遍历所有的规格
                var specList = $(v).find('.specBody tr');
                $.each(specList,function (si,sv) {
                    var package_id = $(sv).find('select[name=packages]').val();
                    if(package_id==''){errmsg='请检查所有套餐';return false;}
                    var spec_id = $(sv).find('select[name=specs]').val();
                    if(spec_id==''){errmsg='请检查所有规格';return false;}
                    var people_num = $(sv).find('input[name=people_num]').val();
                    if(parseInt(people_num)<1){errmsg='请检查购票人数，至少为1';return false;}
                    var package_name = $(sv).find('select[name=packages] option:selected').text();
                    var spec_name = $(sv).find('select[name=specs] option:selected').text();
                    var cost = $(sv).find('input[name=cost]').val();
                    var sale = $(sv).find('input[name=sale_price]').val();
                    specsData.push({
                        package_id:package_id,
                        p_name:package_name,
                        spec_id:spec_id,
                        s_name:spec_name,
                        people_num:people_num,
                        cost:cost,
                        sale:sale
                    });
                })
                if(errmsg!=''){return false;}
                //组装数据
                jsonData.push({
                    days:days,
                    poi_id:poi_id,
                    ticket_id:ticket_id,
                    name:name,
                    currency:currencyCode,
                    rate:rate,
                    cost:costPrice,
                    sale:salePrice,
                    specsData:specsData
                })
                console.log(jsonData)

            })

            if(errmsg!=''){layer.msg(errmsg);return false;}

            return JSON.stringify(jsonData);
        }


        //提交操作
        form.on('submit(submit)',function () {
            var ticket_json = checkAllData();
            // console.log(ticket_json);return false;
            if(!ticket_json){ return false;}
            $.post("{:url('admin/product/ajaxUpdProductTicketData',['id'=>$id])}",{ticket_json:ticket_json},function (res) {
                layer.msg(res.msg);
                if(res.code>0){
                    setTimeout(function(){
                        //关闭当前页
                        var index = parent.layer.getFrameIndex(window.name);//获取当前的索引
                        parent.layer.close(index);
                    },1000)
                }
            })
            return false;
        })

    })
</script>
</body>

</html>